" vim plugin for oschina's tweet
" Maintainer: justin <gschen.cn@gmail.com>
" Last Updated: 04 June 2013

" Changes:
" TODO:
" v 0.1:
"   * first edition, just for fun
"---------------------------------------

" check the vim supports python
if !has('python')
    echo 'Error: Required vim compile with +python'
    finish
endif

" define oschina's vim command
command! -nargs=0 OscLogin exec('py Oschina().login()')
command! -nargs=0 OscLogout exec('py Oschina().logout()')
command! -nargs=1 OscTweet exec('py Oschina().tweet(<f-args>)')
command! -nargs=1 OscCityTweet exec('py Oschina().cityTweet(<f-args>)')
command! -nargs=0 OscTopTweet exec('py Oschina().listTopTweet()')
"command! -nargs=* OscReTweet exec('py Oschina().reTweet(<f-args>)')
command! -nargs=* OscReply exec('py Oschina().reply()')
command! -nargs=* OscReturn exec('py Oschina().refresh()')

python << EOF
import requests 
import hashlib
from bs4 import BeautifulSoup
import vim

username = "YOUR USERNAME"
password = "YOUR PASSWORD"

edit = 1

class Oschina:

    '''
    switch vim to edit on mode
    '''
    def editOn(self):
        global edit
        if not edit:
            edit = 1
        for i in ['i','a','s','o','I','A','S','O']:
            vim.command('unmap '+i)

    '''
    switch vim to non-edit mode
    '''
    def editOff(self):
        global edit
        if edit:
            edit = 0
        for i in ['i','a','s','o','I','A','S','O']:
            vim.command('map '+i+' <nop>')


    ''' delete two vim buffers: osc and tmp
    '''
    def logout(self):
        vim.command('bdelete! osc')
        vim.command('bdelete! tmp')
        self.editOn()

    def __init__(self):
        pass

        '''
        get cookies info from tmp buffer
        '''
    def getCookieFromBuf(self):
        vim.command('buffer tmp')
        cookie = vim.current.buffer[0]
        vim.command('buffer osc')
        return cookie

        '''
        get userId and userCode from tmp buffer
        '''
    def getUserIdAndUserCodeFromBuf(self):
        vim.command('buffer tmp')
        userId = vim.current.buffer[1]
        userCode = vim.current.buffer[2]
        vim.command('buffer osc')
        return userId, userCode


        ''' get other essential info such as userId and userCode after login success.
        '''
    def getParams(self):
        soup = self.getHomePage()
        self.saveUserIdAndCode(soup)

           
    def login(self):
        # create two buffers: osc and tmp
        # osc - display osc info    
        # tmp - save cookies and other info such as userId, userCode
        vim.command('badd osc')
        vim.command('badd tmp')

        payload = {'email':username,'pwd':hashlib.sha1(password).hexdigest(),'save_login':'1'}
        headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 '}
        url = 'http://www.oschina.net/action/user/hash_login'
        s = requests.Session()
        r = s.post(url, data=payload, headers=headers)
        self.session = s

        name = ""
        value = ""
        for cookie in s.cookies:
            name = cookie.name
            value = cookie.value

        """ 
        switch to tmp buffer, and save cookies
        """
        vim.command('buffer tmp')
        vim.current.buffer[0] = '%s=%s'%(name,value)
        vim.command('buffer osc')

        ''' save other essential infos such as userId, userCode
        '''
        self.getParams()
        self.refresh()

    def cityTweet(self,msg):
        soup = self.getHomePage()
        #userId, userCode = self.getUserIdAndCode(soup)

        url = "http://city.oschina.net/action/group/pub_tweet"
        payload = {'user':self.userId, 'user_code':self.userCode, 'attachment':'0', 'msg':msg,'group':'12360'}
        headers={'user-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 ','referer':'http://city.oschina.net/shanghai'}
        r=self.session.post(url,data=payload,headers = headers)
        #print r.text
        print "tweet success."
        #self.cb.append(r.text)
        #self.cb.append("tweet success")
        #vim.current.buffer[0].append(r.text)
        #vim.current.buffer[0].append("tweet success.")


    def tweet(self,msg):
        userId,userCode = self.getUserIdAndUserCodeFromBuf()
        url = 'http://my.oschina.net/action/tweet/pub'
        payload = {'user':userId, 'user_code':userCode, 'attachment':'0', 'msg':msg}
        headers={'user-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 ','referer':'https://www.oschina.net/home/login?goto_page=http%3A%2F%2Fwww.oschina.net%2F','cookie':self.getCookieFromBuf()}
        r=requests.post(url,data=payload,headers = headers)
        print r.text
        print "tweet success."
        self.refresh()

    def getHomePage(self):
        cookie = self.getCookieFromBuf()
        headers={'user-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 ','referer':'https://www.oschina.net/home/login?goto_page=http%3A%2F%2Fwww.oschina.net%2F','cookie':cookie}
        #resp = self.session.get("http://my.oschina.net/gschen",headers=headers)
        resp = requests.get("http://my.oschina.net/gschen",headers=headers)
        soup = BeautifulSoup(resp.text)
        return soup

        
    #save userId and userCode into vim buffer tmp
    def saveUserIdAndCode(self,soup):
        userCode= soup('input', {'name':'user_code'})[0]['value'].encode('utf-8')
        userId= soup('input', {'name':'user'})[0]['value'].encode('utf-8')

        # switch to tmp vim buffer and save userId,userCode
        vim.command('buffer tmp')
        vim.current.buffer.append(userId)
        vim.current.buffer.append(userCode)
        vim.command('buffer osc')

    '''

    '''
    def newBlog(self):
        pass

    def listBlog(self):
        pass

    def getIndexPage(self):
        url = "http://www.oschina.net/"
        headers={'user-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 ','referer':'https://www.oschina.net/home/login?goto_page=http%3A%2F%2Fwww.oschina.net%2F'}
        resp = self.session.get(url,headers=headers)
        return BeautifulSoup(resp.text)

    def listTopTweet(self):
        vim.command('buffer osc')
        try:
            url = "http://www.oschina.net/"
            headers = {'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'}
            resp = requests.get(url, headers=headers)
            soup = BeautifulSoup(resp.text)

            topTweets = soup("ul",class_="TopTweets")[0].find_all("li")

            i = 1
            del vim.current.buffer[:]
            vim.current.buffer[0]="----------------------Oschina Tweets--------------------"
            for tag in topTweets:
                user =  tag("span", class_="user")[0].find("a").string
                date = tag("span",class_="time")[0].find('a').string
                log = tag("span", class_="log")[0].text.replace('\n','\t\t')
                #log = tag("span", class_="log")[0].contents[0].string+"123""


                replyUrl = tag("span",class_="time")[0].find('a')['href']
                a = len(replyUrl.split('/'))
                logId = replyUrl.split('/')[a-1]
                #cont = "[%d]%s|%s|%s"%(i, user,date,logId)
                cont = "[%d]%s|%s|%s|%s|%s"%(i, user,log,date,logId,replyUrl)
                vim.current.buffer.append(cont.encode('utf-8'))

                i += 1
                self.delimeter()
                #dele = '-------------------------------------'
                #vim.current.buffer.append(dele.encode('utf-8'))
                vim.command('set nomodified')
            self.editOff()
            vim.current.window.cursor = (2, 0)

            vim.command('map <enter> : py Oschina().replyEditMode()<cr>')
            vim.command('map <F5> : py Oschina().refresh()<cr>')
        except Exception,e:
            print e

    def refresh(self):
        del vim.current.buffer[:]
        self.listTopTweet()

    def getHeaders(self):
        headers={'user-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 ','referer':'https://www.oschina.net/home'}
        return headers
        
    def replyList(self, url):
        resp = requests.get(url,headers = self.getHeaders())
        soup = BeautifulSoup(resp.text)
        #replyList = dict()
        replyList = []

        postTags = soup('div',class_='post')

        for tag in postTags:
            if len(tag('a')) != 0:
                #key = tag('a')[0].string.encode('utf-8')
                #replyList[key] = 'value'
                replyList.append(tag.text.encode('utf-8').replace('\n',' '))

        return replyList


    def delimeter(self):
        vim.current.buffer.append('------------------------------------------------------------')

    def displayReply(self, buf, url):
        replyList = self.replyList(url)
        for sss in replyList:
            buf.append('----> %s'%sss)


    def replyEditMode(self):
        row, col = vim.current.window.cursor

        tt = len(vim.current.buffer[row-1].split('|')) 
        replyUrl = vim.current.buffer[row-1].split('|')[tt-1]
        id = vim.current.buffer[row-1].split('|')[tt-2] 
        content = vim.current.buffer[row-1].split('|')[tt-4] 
        user = vim.current.buffer[row-1].split('|')[tt-5] 

        del vim.current.buffer[:]

        self.editOn()
        vim.current.buffer[0] = 'LogId:\t\t%s'%id
        vim.current.buffer.append('User:\t\t%s'%user.split(']')[1])
        vim.current.buffer.append('Content:\t%s'%content)
        vim.current.buffer.append('Reply List:\t%s'%replyUrl)
        
        self.delimeter()
        vim.current.buffer.append('Reply info:')
        self.displayReply(vim.current.buffer,replyUrl)
        #replyList = self.replyList(replyUrl)
            

        #for key,value in replyList.items():
        #    vim.current.buffer.append('--%s:\t\t%s'%(key,value))


        self.delimeter()
        vim.current.buffer.append('Please reply as follow, after editing done you could use command OscReply to send your reply.')
        self.delimeter()

        vim.current.window.cursor = (len(vim.current.buffer),0)
    
    def reply(self):
        logId = vim.current.buffer[0].split(':')[1].strip()
        msg = vim.current.buffer[len(vim.current.buffer)-1:]
        self.reTweet(logId, msg)
        self.refresh()

    # according to logId and msg to reply msg.   
    def reTweet(self, logId, msg):
        url = 'http://my.oschina.net/action/tweet/rpl'
        userId,userCode = self.getUserIdAndUserCodeFromBuf()
        payload={'log':logId,'user':userId,'msg':msg}
        headers={'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36','referer':'http://my.oschina.net/gschen','cookie':self.getCookieFromBuf()}
        #resp = requests.post(url, data=payload, headers= headers)
        resp = requests.post(url, data=payload, headers= headers)
        print resp.text
EOF
